import { getLayoutProps } from "@/common/layout/getProps";
import GlobalClasses from "@/styles/globalClasses.module.scss";
import { BackwardOutlined, DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button,
  Descriptions, Divider,
  Form,
  Input, message, Modal,
  Row, Select,
  Space, Table, type TableColumnsType, type TableProps,
} from "antd";
import dayjs from "dayjs";
import { useRouter } from "next/router";
import { type Key, useEffect, useState } from "react";
import styles from "./index.module.scss";

type TableDataType = Record<string, any>;
type TableRowSelection<T> = TableProps<T>["rowSelection"];

export const VoterConfirmCU = () => {
  const router = useRouter();
  const { query } = router;
  const { id, type } = query;
  const [form] = Form.useForm();
  const [applicationData, setApplicationData] = useState<Partial<Record<string, any>>[]>([]);
  const [editForm] = Form.useForm()
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([])

  const isAdd = !id && !type;
  const isEdit = !!id && !type;
  const isDetail = !!id && (type === "detail");

  const getDetailById = () => {
    if (isEdit || isDetail) {
      form.setFieldsValue({
        field1: `BMPJ2404120011}`,
        field2: "部门",
        field3: "部门",
        field4: "系统创新部",
        field5: "季度",
        field6: "奥德标",
        field7: dayjs(new Date()),
        field8: "奥德标",
        field9: dayjs(new Date()),
        field10: '待提交',
      });
    }
  }

  const getApplicationData = () => {
    setApplicationData(Array(3).fill(0).map((_, i) => {
      return {
        field1: `项目名称${i + 1}`,
        field2: '项目内容',
        field3: "1.完成建设内内蒙分公司上线上收\n" +
          "作。2跟踪完善宝信系统功能。3.\n" +
          "组织开展个人绩效评价。",
        field4: "对新成立的建设公司内蒙分公\n" +
          "司采购应付业务静态模板收\n" +
          "集，组织顾问进行系统配置",
        field5: "3",
        field6: "说明说明说明说明",
      }
    }))
  }

  useEffect(() => {
    if (isEdit || isDetail) {
      getDetailById();
    } else {
      form.setFieldsValue({})
    }
    getApplicationData();
  }, []);

  const applicationColumns: TableColumnsType = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text: string, _record, index: number) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "工号",
      dataIndex: "votePersonId"
    },
    {
      align: "center",
      title: "姓名",
      dataIndex: "votePersonName"
    },
    {
      align: "center",
      title: "岗位",
      dataIndex: "field3"
    },
    {
      align: "center",
      title: "职级",
      dataIndex: "field4"
    },
    {
      align: "center",
      title: "政治面貌",
      dataIndex: "field5"
    }
  ]

  const onSelectChange = (keys: Key[]) => {
    console.log(keys);
    setSelectedRowKeys(keys)
  }

  const rowSelection: TableRowSelection<TableDataType> = {
    selectedRowKeys,
    onChange: onSelectChange
  }

  const handleOk = () => {
    message.success("edit success!")
    setTimeout(() => {
      setOpen(false);
    }, 500)
  }

  const handleCancel = () => {
    setOpen(false);
  }

  return (
    <>
      <PageContainer header={{
        title: false
      }}>
        <div className={[styles.formCard, "mb-[20px]"].join(" ")}>
          <div
            className={[GlobalClasses.title, "title"].join(" ")}>{(isEdit && !isDetail) ? "编辑" : isAdd ? "新增" : ""}投票人信息{isDetail ? "详情" : ""}</div>

          <div className="header">
            <div className={[GlobalClasses.subTitle, 'title'].join(" ")}>--基本信息--</div>
          </div>

          <Descriptions column={4} items={[
            {
              label: "单据编号",
              children: "BMPJ2404120011"
            },
            {
              label: "申请部门",
              children: "创新部"
            },
            {
              label: "申请人",
              children: "赵三"
            },
            {
              label: "申请日期",
              children: "2024-1-1"
            }
          ]}/>

          <Divider className={'mb-[20px] mt-0'}/>

          <div className="header">
            <div className={[GlobalClasses.subTitle, 'title'].join(" ")}>--结果列表--</div>
            {
              !(isAdd || isEdit) ?
                null :
                (
                  <Row justify={"end"} className={"mb-[20px]"}>
                    <Space>
                      <Button type={'primary'} icon={<BackwardOutlined />}>返回</Button>
                      <Button type={'primary'} icon={<PlusOutlined/>} onClick={() => {
                        setCurrentEdit({});
                        editForm.resetFields();
                        setOpen(true);
                      }}>新增</Button>
                      <Button disabled={selectedRowKeys.length !== 1} type={'primary'} icon={<EditOutlined/>}
                              onClick={() => {
                                setCurrentEdit(applicationData.find(item => (item.field1 === selectedRowKeys[0]))!)
                                editForm.resetFields();
                                setOpen(true);
                              }}>编辑</Button>
                      <Button type={'primary'} icon={<DeleteOutlined/>} danger>删除</Button>
                    </Space>
                  </Row>
                )
            }
          </div>

          <Table
            rowKey={'field1'}
            dataSource={applicationData}
            columns={applicationColumns}
            rowSelection={rowSelection}
          ></Table>

          <Modal
            open={open}
            title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}投票人信息`}
            afterClose={() => editForm.resetFields()}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={'提交'}
            cancelText={'取消'}
            footer={(_, {OkBtn, CancelBtn}) => (
              <>
                <CancelBtn/>
                <OkBtn/>
              </>
            )}
          >
            <Form form={editForm} initialValues={currentEdit} labelCol={{span: 4}} labelAlign={'left'}>
              <Form.Item
                label={'评优活动'}
                name={'field1'}
              >
                <Input disabled value={'2024绩效评优华东'}></Input>
              </Form.Item>
              <Form.Item
                label={'姓名'}
                name={'field2'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'岗位'}
                name={'field3'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'职级'}
                name={'field4'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'政治面貌'}
                name={'field5'}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </PageContainer>
    </>
  )
}

export const getServerSideProps = getLayoutProps;
export default VoterConfirmCU;
